<?php


namespace app\home\severs;


use think\Exception;
use think\facade\Db;

class InReceiptSever extends Base
{
    public static function doSure($param,$uid=0)
    {
        $id = $param['id'] ?? 0;
        if (!$id) {
            return self::jump(1, '参数缺失');
        }
        $info = Db::connect('company')->name('in_receipt')->where('id', $id)->find();
        if (!$info || $info['status'] != 1) {
            return self::jump(1, '参数有误');
        }
        $mx = Db::connect('company')->name('in_receipt_detail')->where('status', 1)->where('in_receipt_id', $id)->select();
        $mx = $mx->toArray() ?? [];
        if (!$mx) {
            return self::jump(1, '请添加明细');
        }
        Db::connect('company')->startTrans();
        try {

            if ($info['type'] == '销售退货') {
                $gzData = [];

                foreach ($mx as $m) {
                    $price=Db::connect('company')->name('purveyor_price')
                        ->where('status',1)->where('purveyor_id',$info['punter_id'])
                        ->where('material_dossier_id',$m['material_dossier_id'])
                        ->where('time',date('Y-m'))->order('time DESC')->limit(1)->value('price');
                    $price=$price??0;
                    $gzData[] = [
                        'punter_id' => $info['punter_id'],
                        'material_dossier_id' => $m['material_dossier_id'],
                        'create_user' => $uid,
                        'orderNum' => orderNum('GZH'),
                        'orderDate' => date('Y-m-d'),
                        'in_receipt_detail_id' => $m['id'],
                        'g_orderNum' => $info['orderNum'],
                        'type' => $info['type'],
                        "num" => -$m['num'],//销售退货为负数
                        'price'=>$price,
                        'countPrice'=>$price*$m['num'],
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                }
                Db::connect('company')->name('sale_hanging_bill')->insertAll($gzData);
            }
            if ($info['type']=='采购收货'){
                $gzData = [];
                foreach ($mx as $m) {
                    $price=Db::connect('company')->name('purveyor_price')
                        ->where('status',1)->where('purveyor_id',$info['punter_id'])
                        ->where('material_dossier_id',$m['material_dossier_id'])
                        ->where('time',date('Y-m'))->order('time DESC')->limit(1)->value('price');
                    $price=$price??0;
                    $gzData[] = [
                        'punter_id' => $info['punter_id'],
                        'material_dossier_id' => $m['material_dossier_id'],
                        'create_user' => $uid,
                        'orderNum' => orderNum('GZH'),
                        'orderDate' => date('Y-m-d'),
                        'in_receipt_detail_id' => $m['id'],
                        'g_orderNum' => $info['orderNum'],
                        'type' => $info['type'],
                        'h_type' => 1,
                        "num" => $m['num'],
                        'price'=>$price,
                        'countPrice'=>$price*$m['num'],
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                }
                Db::connect('company')->name('sale_hanging_bill')->insertAll($gzData);
            }
            Db::connect('company')->name('in_receipt')->where('id', $id)->update(['incom_user' => $uid, 'status' => 2, 'update_time' => time(), 'checkTime' => time()]);
            Db::connect('company')->name('in_receipt_detail')->where('status', '1')
                ->where('in_receipt_id', $id)->update(['status' => 2, 'update_time' => time()]);
            $params=request()->param();
            $params['id']=$id;
            add_log('check', $id, $params, '入库单',$uid);
            Db::connect('company')->commit();
        } catch (\Exception $e) {
            Db::connect('company')->rollback();
            return self::jump(1, '操作失败:' . $e->getMessage());
        }
        return self::jump(0, '操作成功');
}

    public static function create($param,$uid){
        $printCompany=config('config.companyName');
        Db::connect('company')->StartTrans();
        try {
            $data=[
                'type' => '盘盈入库',
                'incomTime' => $param['incomTime']??date('Y-m-d'),
                'status' => $param['status']??1,
                'printCompany' => $param['printCompany']??$printCompany[0],
                'punter_id' => $param['punter_id']??'',
                'orderNum'=>$param['orderNum']??'',
                'oCode'=>$param['oCode']??'',
                'create_time'=>time(),
                'create_user'=>$uid,
                'update_time'=>time(),
            ];
        $id=Db::connect('company')->name('in_receipt')->insertGetId($data);
        if (isset($param['wlData'])&&$param['wlData']){
            $mxList=[];
            foreach ($param['wlData'] as $v){
                $mxList[]=[
                    'in_receipt_id' => $id,
                    'material_dossier_id' => $v['mdId'],
                    'num' => 0,
                    'locator' => 1,
                    'warehouse_id' => $v['warehouse_id'],
                    'i_remark' =>'新建物料',
                    'create_time' => time(),
                    'update_time' => time()
                ];
            }
            Db::connect('company')->name('in_receipt_detail')->insertAll($mxList);
        }else{
            $mxData = [
                'in_receipt_id' => $id,
                'material_dossier_id' => $param['mdId'],
                'num' => 0,
                'locator' => 1,
                'warehouse_id' => $param['warehouse_id'],
                'i_remark' =>'新建物料',
                'create_time' => time(),
                'update_time' => time()
            ];
            Db::connect('company')->name('in_receipt_detail')->insert($mxData);
        }

            $sures=InReceiptSever::doSure(['id'=>$id],$uid);
            if ($sures['code']==1){
                throw new Exception($sures['msg']);
            }
            add_log('add', $id, $param, '入库单',$uid);
            Db::connect('company')->commit();
        }catch (\Exception $e){
            Db::connect('company')->rollback();
            return self::jump(1,$e->getMessage());
        }

        return self::jump();

}
}